/**
 * Copyright 2004 - 2007 Blue Bamboo International Inc. 
 *           All rights reserved.
 *
 *
 * Blue Bamboo PROPRIETARY/CONFIDENTIAL.
 *
 */

package com.bambamboo.st.socket.server.netty;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ConnectionlessBootstrap;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.socket.nio.NioDatagramChannelFactory;

import com.bambamboo.st.AbstractIOServer;
import com.bambamboo.st.socket.server.SocketConnectionBean;

/**
 * UDP Server implemented with JBoss Netty.
 * <p>
 * Binding UDP port and delegate all request to <code>IProecess</code>
 * </p>
 * 
 * @author Nick.Tan
 * @since 2.0.0
 */
public class NettyUDPServer extends AbstractIOServer {

	@Override
	public void startup() throws Exception {
		ChannelFactory factory = new NioDatagramChannelFactory(Executors.newCachedThreadPool());

		ConnectionlessBootstrap bootstrap = new ConnectionlessBootstrap(factory);
		ChannelPipeline pipeline = bootstrap.getPipeline();
		SocketConnectionBean bean = (SocketConnectionBean) getConnectionBean();
		AbstractChannelHandler channelHandler = new DefaultChannelHandler();
		channelHandler.setConfigurationBean(bean);
		pipeline.addLast("handler", channelHandler);

		String port = bean.getPort();
		bootstrap.bind(new InetSocketAddress(Integer.parseInt(port)));
	}

	@Override
	public String getType() {
		return "UDP";
	}
}
